use gloo::console;
use std::rc::Rc;
use yew::{
    function_component, functional::Reducible, html, use_reducer, Children, ContextProvider, Html,
    Properties, UseReducerHandle,
};

#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Msg {
    pub msg_show: bool,
    pub msg_txt: String,
}

pub enum MsgAction {
    ShowMsg(String),
    HideMsg,
}

impl Reducible for Msg {
    type Action = MsgAction;

    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
        let next_state = match action {
            MsgAction::ShowMsg(ref msg) => {
                console::log!(format!("ShowMsg:{}", msg.to_owned()));

                Self {
                    msg_show: true,
                    msg_txt: msg.clone(),
                }
            }
            MsgAction::HideMsg => Self {
                msg_show: false,
                ..Default::default()
            },
        };
        next_state.into()
    }
}

pub type MessageContext = UseReducerHandle<Msg>;

#[derive(Properties, Debug, PartialEq)]
pub struct MessageProviderProps {
    #[prop_or_default]
    pub children: Children,
}

#[function_component]
pub fn MessageProvider(props: &MessageProviderProps) -> Html {
    let msg = use_reducer(Msg::default);

    html! {
        <ContextProvider<MessageContext> context={msg}>
            {props.children.clone()}
        </ContextProvider<MessageContext>>
    }
}
